package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qianying.comment.CommonResult;
import com.qianying.comment.JsonUtil;
import com.qianying.comment.ResultCode;
import com.qianying.dto.TockenDTO;
import com.qianying.entity.SysRole;
import com.qianying.entity.SysUser;
import com.qianying.entity.SysUserRole;
import com.qianying.exception.MyServiceException;
import com.qianying.mapper.SysUserMapper;
import com.qianying.mapper.SysUserRoleMapper;
import com.qianying.service.SysRoleService;
import com.qianying.service.SysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianying.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Map;

import com.qianying.comment.AesUtil;

import javax.xml.stream.events.Comment;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author check
 * @since 2025-07-15
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    SysUserMapper userMapper;
    @Autowired
    SysRoleService roleService;

    @Autowired
    SysUserRoleMapper userRoleMapper;

    @Override
    public CommonResult<LoginVo> login(SysUser sysUser) {
        if (sysUser == null) {
            return CommonResult.failed("登录对象不能为空！");
        }
        if (sysUser.getUsername().trim().isEmpty() || sysUser.getPassword().trim().isEmpty()) {
            return CommonResult.failed("用户名或密码不能为空！");
        }
        CommonResult<SysUser> userRes = getByUsername(sysUser.getUsername());
        if (userRes.getCode() == ResultCode.FAILED.getCode()) {
            return CommonResult.failed(userRes.getMessage());
        }

        if (!sysUser.getPassword().equals(userRes.getData().getPassword())) {
            return CommonResult.failed("密码不对！");
        }
        Long rouleId = userRes.getData().getRoleId();
        if (rouleId == -1) {
            return CommonResult.failed("没有分配角色，暂时不能登录，请联系管理员！");
        }

        if (userRes.getData().getEnabled()) {
            return CommonResult.failed("当前客户被禁用，请联系管理员！");
        }

        CommonResult<SysRole> roleRes = roleService.getByRoleId(rouleId);

        if (roleRes.getCode() == ResultCode.FAILED.getCode()) {
            return CommonResult.failed(roleRes.getMessage());
        }

        if (roleRes.getData().getStatus() < 1) {
            return CommonResult.failed("当前角色已经被禁用，请联系管理员！");
        }

        return createLoginVO(userRes.getData().getId(), roleRes.getData().getId(), roleRes.getData().getRoleCode(), "登录成功！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 事务注解
    public CommonResult<LoginVo> register(SysUser user) {
        if (user == null || user.getUsername().isEmpty() || user.getPassword().isEmpty() || user.getPhone().isEmpty()) {
            return CommonResult.failed("注册字段信息不能为空！");
        }
        CommonResult<SysUser> byNameRes = getByUsername(user.getUsername());
        if (byNameRes.getCode() != ResultCode.FAILED.getCode()) {
            return CommonResult.failed("该用户已存在！");
        }
        CommonResult<SysUser> byPhoneRes = getByPhone(user.getPhone());
        if (byPhoneRes.getCode() != ResultCode.FAILED.getCode()) {
            return CommonResult.failed("该电话号码已经被注册！");
        }
        if (user.getRoleId() == null) {
            return CommonResult.failed("角色Id为空，不能组注册");
        }
        CommonResult roleRes = roleService.getByRoleId(user.getRoleId());
        if (!roleRes.isSuccess()) {
            return CommonResult.failed("角色Id非法，不能注册！");
        }

        user.setEnabled(false);
        user.setId(null);
        int addUserNum = userMapper.insert(user);
        if (addUserNum < 1) {
            throw new MyServiceException(CommonResult.failed("插入用户错误"));
        }


        return createLoginVO(user.getId(), user.getRoleId(), "-1", "注册成功！");
    }

    @Override
    public CommonResult<SysUser> getByUsername(String userName) {

        if (userName.isEmpty()) {
            return CommonResult.failed("参数错误！");
        }

        SysUser sysUser = userMapper.selectByUsername(userName);

        if (sysUser == null) {
            // 用户不存在，返回错误信息
            return CommonResult.failed("该用户不存在！");
        }

        return CommonResult.success(sysUser, "查询成功！");
    }

    @Override
    public CommonResult<SysUser> getByPhone(String phone) {
        if (phone.isEmpty()) {
            return CommonResult.failed("电话号码不能为空！");
        }
        SysUser sysUser = userMapper.selectByPhone(phone);
        if (sysUser == null) {
            // 用户不存在，返回错误信息
            return CommonResult.failed("该号码未注册！");
        }

        return CommonResult.success(sysUser, "查询成功！");
    }


    private CommonResult<LoginVo> createLoginVO(Long userID, Long roleId, String roleKey, String msg) {

        TockenDTO tockenDTO = new TockenDTO(userID, roleId);

        try {
            String json = JsonUtil.toJson(tockenDTO);
            String tocken = AesUtil.encrypt(json);
            //roleKey 是为了让那个前端知道是哪个角色，根据角色显示界面
            LoginVo loginVo = new LoginVo(tocken, roleKey);
            return CommonResult.success(loginVo, msg);
        } catch (Exception e) {
            return CommonResult.failed("创建session 失败！");
        }
    }

    @Override
    public CommonResult<SysUser> updateUserSelective(SysUser user) {
        // 空判断，确保传入的 user 对象不为空
        if (user == null || user.getId() == null) {
            return CommonResult.failed("用户对象或用户ID为空，无法更新");
        }

        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUser::getId, user.getId());

        // 对每个字段进行非空判断，只更新非空的字段
        if (user.getEnabled() != null) {
            updateWrapper.set(SysUser::getEnabled, user.getEnabled());
        }
        if (StringUtils.hasText(user.getPhone())) {
            updateWrapper.set(SysUser::getPhone, user.getPhone());
        }
        if (user.getCreateTime() != null) {
            updateWrapper.set(SysUser::getCreateTime, user.getCreateTime());
        }
        if (user.getRoleId() != null) {
            CommonResult<?> roleRe = roleService.getByRoleId(user.getRoleId());
            if (!roleRe.isSuccess()) {
                return CommonResult.failed(roleRe.getMessage());
            }
            updateWrapper.set(SysUser::getRoleId, user.getRoleId());
        }
        int num = userMapper.update(updateWrapper);
        return num > 0 ? CommonResult.success(user, "用户更新成功！") : CommonResult.failed("更新用户失败");
    }

    @Override
    public CommonResult<IPage<SysUser>> getUserPageByRoleId(Page<SysUser> page, SysUser queryParam) {
        // 构建查询条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();

        // 角色ID查询：0表示未分配角色（roleId为null或0），其他值表示精确匹配
        if (queryParam.getRoleId() != null) {
            if (queryParam.getRoleId() == 0) {
                // 查询未分配角色的用户（roleId为null或0）
                queryWrapper.and(wrapper -> wrapper.isNull(SysUser::getRoleId).or().eq(SysUser::getRoleId, 0));
            } else {
                // 精确匹配指定角色ID
                queryWrapper.eq(SysUser::getRoleId, queryParam.getRoleId());
            }
        }

        // 用户名模糊查询
        if (StringUtils.hasText(queryParam.getUsername())) {
            queryWrapper.like(SysUser::getUsername, queryParam.getUsername());
        }

        // 手机号模糊查询
        if (StringUtils.hasText(queryParam.getPhone())) {
            queryWrapper.like(SysUser::getPhone, queryParam.getPhone());
        }

        // 用户状态精确查询（0-无效，1-有效）
        if (queryParam.getEnabled() != null) {
            queryWrapper.eq(SysUser::getEnabled, queryParam.getEnabled());
        }

        // 按创建时间降序排序（最新创建的在前）
        queryWrapper.orderByDesc(SysUser::getCreateTime);

        // 执行分页查询
        IPage<SysUser> userPage = baseMapper.selectPage(page, queryWrapper);
        if (!userPage.getRecords().isEmpty()) {
            CommonResult<Map<Long, String>> roleNameMapRes = roleService.getRoleNameMap();

            if (roleNameMapRes.isSuccess()) {
                Map<Long, String> roleNameMap = roleNameMapRes.getData();
                if (!roleNameMap.isEmpty()) {
                    for (SysUser record : userPage.getRecords()) {
                        if (roleNameMap.containsKey(record.getRoleId())) {
                            record.setRoleName(roleNameMap.get(record.getRoleId()));
                        } else {
                            record.setRoleName("未分配角色");
                        }
                    }
                }
            }
        }

        return CommonResult.success(userPage);
    }

    @Override
    public CommonResult<SysUser> updateUserInfo(SysUser user, Boolean byUserSelfBol) {
        // 1. 校验参数
        if (user == null || user.getId() == null) {
            return CommonResult.failed("用户ID不能为空");
        }

        // 2. 检查用户是否存在
        SysUser existingUser = baseMapper.selectById(user.getId());
        if (existingUser == null) {
            return CommonResult.failed("用户不存在");
        }

        // 3. 构建动态更新条件（只更新非空字段）
        LambdaUpdateWrapper<SysUser> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SysUser::getId, user.getId());

        // 用户名非空则更新
        if (StringUtils.hasText(user.getUsername())) {
            // 可添加用户名唯一性校验
            updateWrapper.set(SysUser::getUsername, user.getUsername());
        }

        // 跟新用户别名
        if (StringUtils.hasText(user.getAnotherName())) {
            // 可添加用户名唯一性校验
            updateWrapper.set(SysUser::getAnotherName, user.getAnotherName());
        }

        // 跟新用描述
        if (StringUtils.hasText(user.getDes())) {
            // 可添加用户名唯一性校验
            updateWrapper.set(SysUser::getDes, user.getDes());
        }

        // 手机号非空则更新
        if (StringUtils.hasText(user.getPhone())) {
            // 可添加手机号格式校验
            updateWrapper.set(SysUser::getPhone, user.getPhone());
        }
        if (!byUserSelfBol) { // 角色ID非空则更新（允许0表示未分配）
            if (user.getRoleId() != null) {
                updateWrapper.set(SysUser::getRoleId, user.getRoleId());
            }

            // 用户状态非空则更新
            if (user.getEnabled() != null) {
                updateWrapper.set(SysUser::getEnabled, user.getEnabled());
            }
        }

        // 4. 执行更新操作
        int rows = baseMapper.update(null, updateWrapper);
        if (rows > 0) {
            // 5. 返回更新后的完整用户信息
            SysUser updatedUser = baseMapper.selectById(user.getId());
            return CommonResult.success(updatedUser);
        } else {
            return CommonResult.failed("更新失败，未找到可更新的内容或数据未变化");
        }
    }

}
